package com.erastep.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import com.erastep.pojo.User;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import flex.messaging.io.ArrayCollection;
import flex.messaging.io.amf.ASObject;
import flex.messaging.io.amf.translator.ASTranslator;


public class CommonMethod {
   public static String getProperties(String name){
	   InputStream is =CommonMethod.class.getResourceAsStream("/common.properties");
       Properties p = new Properties();
       try {
		p.load(is);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   return p.get(name).toString();
   }
	/**
	 * @author Administrator smj �����������ת��Ϊxml
	 * @param object 
	 * @return 
	 * @author */
  public static String xmlObject(Object object,String...strings) throws Exception {   
      // 
      Class<? extends Object> classType = object.getClass();   
      Field fields[] = classType.getDeclaredFields();   
      String str = object.getClass().toString().substring(object.getClass().toString().lastIndexOf(".")+1);
      String s = "   <"+str+">\n";
      for (int i = 0; i < fields.length; i++) { 
          Field field = fields[i];   
          String fieldName = field.getName();   
          if(strings.length > 0){
        	  if(strings[0].indexOf(fieldName) != -1){
        		  continue;
        	  }else{
        		 
        	  }
          }
          String firstLetter = fieldName.substring(0, 1).toUpperCase(); 
          String getMethodName = "get" + firstLetter + fieldName.substring(1); 
          Method getMethod = classType.getMethod(getMethodName, new Class[] {});
          Object value = getMethod.invoke(object, new Object[] {});   
          if(value == null)
       	   value ="";
          s += "         <"+fieldName+">"+value+"</"+fieldName+">\n";
      }   
      return s+"    </"+str+">\n";   
  }
  /**
   * @author Administrator smj
   * @param list List����
   * @param strings ���˶����в���Ҫѭ���������ֶ�
   * @return String һ������xml��ʽ�ַ�
   * */
  public static String FormatXML(List list,String...strings){
	   	StringBuffer sb = new StringBuffer();
	   	sb.append("<data>\n");
    	for(int i=0;i<list.size();i++){
            try {
 				sb.append(xmlObject(list.get(i),strings));
 			} catch (Exception e) {
 				e.printStackTrace();
 				System.out.print("Create XML Error!");
 			}   
         }
		 sb.append("</data>");
    	return sb.toString();
  }
/**
 * @author Administrator smj
 * @param object ����
 * @param strings ��Ҫ���˵��ֶ�
 * @return json��ʽ�����
  **/
  public static String arrayObject(Object object,String...strings) throws Exception {   
      Class<? extends Object> classType = object.getClass();   
      Field fields[] = classType.getDeclaredFields();   
      String s = "{";
      for (int i = 0; i < fields.length; i++) { 
          Field field = fields[i];   
          String fieldName = field.getName();   
          if(strings.length > 0){
        	  if(strings[0].indexOf(fieldName) != -1){
        		  continue;
        	  }else{
        		 
        	  }
          }
          String firstLetter = fieldName.substring(0, 1).toUpperCase(); 
          String getMethodName = "get" + firstLetter + fieldName.substring(1); 
          Method getMethod = classType.getMethod(getMethodName, new Class[] {});
          Object value = getMethod.invoke(object, new Object[] {});   
          if(value == null)
       	   value ="";
          s += "\""+fieldName+"\":\""+value+"\"";
          if(i < fields.length-1){
        	  s += ",";
          }
      }   
      return s+"}";   
  }
  /**
   * @author Administrator smj
   * @param owner ����
   * @param methodName �������
   * */
  public static Object invokeMethod(Object owner, String methodName, Object[] args)
          throws Exception {
	    try {
		  Class<? extends Object> ownerClass = owner.getClass();
	      Class[] argsClass = new Class[args.length];
	      for (int i = 0, j = args.length; i < j; i++) {
	          argsClass[i] = args[i].getClass();
	      }
	      Method method = ownerClass.getMethod(methodName, argsClass);
	      return method.invoke(owner, args);
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
     
  }
  /**
   * paster ��ֵ��
   * copy   ��ֵ��
   * */
  public  static Object copyValue(Object paster,Object copy){
	  Class<? extends Object> cls = paster.getClass();                        
	  Method methlist[] = cls.getDeclaredMethods();   
	  Class<? extends Object> cop = copy.getClass();
	  Method copm[] = cop.getDeclaredMethods();
	  String strName = "";
	  for(int i = 0;i < copm.length;i++){
		  Method m = copm[i];   
		  if("get".equals(m.getName().substring(0, 3))){
			  strName += m.getName().substring(3, m.getName().length());
			  if(i < copm.length-1){
				  strName += ",";
			  }
		  }
	  }
      for (int i = 0; i < methlist.length; i++) {   
          Method m = methlist[i];   
          if("set".equals(m.getName().substring(0, 3))){
        	 if(strName.indexOf(m.getName().substring(3, m.getName().length())) > -1){
        		try {
            		  invokeMethod(paster,"set"+m.getName().substring(3, m.getName().length()),new Object[]{invokeMethod(copy,"get"+m.getName().substring(3, m.getName().length()),new Object[]{})});
        		    } catch (Exception e) {
					  
				    }
        		 
        	 }
          }
      }
      return cls;
  }
  /**
   *  解析成json对象
   * */
  public static String FormartArray(List list,String...strings){
	   	StringBuffer sb = new StringBuffer();
	   	sb.append("[");
    	for(int i=0;i<list.size();i++){
            try {
 				sb.append(arrayObject(list.get(i),strings));
 				if(i < list.size()-1){
 					sb.append(",");
 				}
 			} catch (Exception e) {
 				e.printStackTrace();
 				System.out.print("Create Array Error!");
 			}   
         }
		 sb.append("]");
    	return sb.toString();
  }
  
  /**
   * @author Administrator smj
   * @param d 传入日期
   * @param day 加天数
   * @return Date 返回新日期
   * */
  public static Date addDate(Date d,long day) throws ParseException { 
	  long time = d.getTime(); 
	  day = day*24*60*60*1000; 
	  time+=day; 
	  return new Date(time); 
  } 
  /**
   * Convert Flex ArrayCollection Object to Java List Object
   * @param arrayCollection
   * @return
   */
  public static ArrayList arrayCollectionToArrayList(ArrayCollection arrayCollection, Class objClass) {
	  ArrayList mObjectList = new ArrayList();
	  ASTranslator mAsTranslator = new ASTranslator();

	  ASObject mASObject;
		  
	  for (int i = 0; i < arrayCollection.size(); i++) {
		  Object mObject = new Object();
		  mASObject = new ASObject();
		  
		  if (!arrayCollection.get(i).getClass().equals(ASObject.class)) {
			  mObjectList = arrayCollection;
			  break;
		  } else {
			  mASObject = (ASObject)arrayCollection.get(i);
			  mASObject.setType(objClass.getName());
			  mObject = (Object)mAsTranslator.convert(mASObject, objClass);
			  mObjectList.add(mObject);
		  }
		  
	  }
	  return mObjectList;
  }
  
  /**
   * Convert FlexObject To JavaObject
   * @param asObject
   * @param objType
   * @return 
   */
  public static Object flexObjectToJavaObject(Object asObject, Class objClass) {
	  Object mObject = new Object();
	  if (asObject.getClass().equals(objClass)) {
		  mObject = asObject;
	  } else if (asObject.getClass().equals(ASObject.class)) {
		  ASTranslator mAsTranslator = new ASTranslator();

		  ((ASObject)asObject).setType(objClass.getName());
		  mObject = (Object)mAsTranslator.convert(asObject, objClass);
	  }
	  return mObject;

  }

  /**
   * @author Administrator smj
   * @param  newPass 新密码
   * @param oldPass 数据库中的密码
   * @return boolean true 验证成功反之失败
   * */
	public static boolean verifyPass(String newPass,String oldPass){
		 boolean flg = false;
		 try {
	      flg = MessageDigest.isEqual(getEncryptPwd(newPass).getBytes(), oldPass.getBytes());
		 } catch (Exception e) {
			e.printStackTrace();
			flg = false;
		 }   
		 System.out.println("开始验证密码...."+newPass+"==="+oldPass+"======="+flg);
		return flg;
	}
	/**
	 * @author Administrator smj
	 * @param text 未加密字符串
	 * @return String 已加密字符串
	 * */
	public static String getEncryptPwd(String text){
		 MessageDigest messageDigest;
		 String pass = null;
	     try {
	      messageDigest = MessageDigest.getInstance("MD5");
		  messageDigest.update(text.getBytes()); 
		  pass = new String(Base64.encode(messageDigest.digest()));
		 } catch (NoSuchAlgorithmException e) {
		    e.printStackTrace();
		 }
		return pass;
	}
	
	/**
	 * @author Jarvis
	 * @param ResultSet 数据集
	 * @param pojo 
	 * @return 注入后的值
	 * */
	public static Object setDataByResultSet(ResultSet rs,Object obj){
		try {
			  Class<? extends Object> classType = obj.getClass();   
		      Field fields[] = classType.getDeclaredFields();   
		      for (int i = 0; i < fields.length; i++) { 
		          Field field = fields[i];   
		          String fieldName = field.getName();   
		          Class<?> cl = field.getType();
		          //String
		          Object value =  null;
		          if(cl == String.class){
		        	  value = rs.getString(fieldName);
		          }else if(cl == Integer.class){
		        	  value = rs.getInt(fieldName);
		          }else if(cl == java.sql.Date.class){
		        	  value = rs.getDate(fieldName);
		          }else if(cl == char.class){
		        	  value = rs.getString(fieldName);
		          }
		          invokeMethod(obj,"set"+(fieldName.charAt(0)+"").toUpperCase()+fieldName.substring(1),new Object[]{value});
		      }   
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return obj;
	}

	public static void main(String[] args) {
		//System.out.println(getEncryptPwd("0123456"));
		try {
		} catch (Exception e) {
			// TODO: handle exception
		}
	
	}
}
